/*
 *  VulnTrace.cpp 
 */

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include "detours.h"

DWORD get_mem_size(char *block)
{
     DWORD     fnum=0,
               memsize=0,     
               *frame_ptr=NULL,
               *prev_frame_ptr=NULL,
               *stack_base=NULL,
               *stack_top=NULL;
     
     __asm mov eax, dword ptr fs:[4]
     __asm mov stack_base, eax
     __asm mov eax, dword ptr fs:[8]
     __asm mov stack_top, eax
     __asm mov frame_ptr, ebp

     if( block < (char *)stack_base && block > (char *)stack_top)
     for(fnum=0;fnum<=5;fnum++)
     {
          if( frame_ptr < (DWORD *)stack_base && frame_ptr > stack_top)
          {
               prev_frame_ptr = (DWORD *)*frame_ptr;

               if( prev_frame_ptr < stack_base && prev_frame_ptr > stack_top)
               {
                    if(frame_ptr < (DWORD *)block && (DWORD *)block < prev_frame_ptr)
                    {     
                         memsize = (DWORD)prev_frame_ptr - (DWORD)block;
                         break;
                    }
                    else
                         frame_ptr = prev_frame_ptr;
               }
          }     
     } 

     return(memsize);
}

DETOUR_TRAMPOLINE(char * WINAPI real_lstrcpynA(char *dest,char *source,int maxlen), lstrcpynA);


char * WINAPI vt_lstrcpynA (char *dest,char *source,int maxlen)
{
        char dbgmsg[1024];
        LPTSTR retval;

        _snprintf(dbgmsg, sizeof(dbgmsg), "[VulnTrace]: lstrcpynA(0x%08x:[%d], %s, %d)\n",dest,get_mem_size(dest), source, max-len);
        dbgmsg[sizeof(dbgmsg)-1] = 0;
        
        OutputDebugString(dbgmsg);

        retval = real_lstrcpynA(dest, source, maxlen);
        
        return(retval);
}

BOOL APIENTRY DllMain(     HANDLE hModule, 
                              DWORD  ul_reason_for_call, 
                              LPVOID lpReserved
                          )
{
    if (ul_reason_for_call == DLL_PROCESS_ATTACH)
     {
               DetourFunctionWithTrampoline((PBYTE)real_lstrcpynA, (PBYTE)vt_lstrcpynA);
     }
    else if (ul_reason_for_call == DLL_PROCESS_DETACH)
     {
          OutputDebugString("[*] Unloading VulnTrace\n");
    }

    return TRUE;
}
